package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.Device;

import com.zzyl.serve.dto.DeviceDataPageReqDto;
import com.zzyl.serve.job.vo.IotMsgNotifyData;
import com.zzyl.serve.job.vo.IotMsgService;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 报警数据Service业务层处理
 * 
 * @author yanbucai
 * @date 2025-05-11
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param deviceData 报警数据
     * @return 报警数据
     */

    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto){
        // 1. 封装条件：name模糊搜索、 functionId精确搜索 、 开始结束时间
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<DeviceData>()
                .eq(StrUtil.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .like(StrUtil.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .between(
                        dto.getStartTime() != null && dto.getEndTime() != null,
                        DeviceData::getAlarmTime,
                        dto.getStartTime(),
                        dto.getEndTime()
                );

        // 2. 执行查询
        List<DeviceData> list = list(queryWrapper);

        return list;
    }
    /**
     * 新增报警数据
     *
     * @param deviceData 报警数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param deviceData 报警数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 批量保存 设备消息数据
     */
    /**
     *  批量保存 设备消息数据
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData data) {

        // 1. 查询设备
        String iotId = data.getHeader().getDeviceId();
        Device device = deviceService.getOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getIotId, iotId)
        );

        // 判断是否为空，如果设备查不到，直接抛出异常终止运行
        if (device == null) {
            throw new RuntimeException("设备不存在");
        }


        // 2. 构建设备数据
        List<IotMsgService> services = data.getBody().getServices();
        // 遍历services，构建DeviceData
        services.forEach(service -> {

            // 取出properties
            Map<String, Object> properties = service.getProperties();

            // 单独处理上报日期时间：
            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            eventTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            LocalDateTime finalEventTime = eventTime;

            // 定义批量保存的list
            List<DeviceData> list = new ArrayList<>();

            properties.forEach((key, value) -> {

                // 构造者模式创建对象
                DeviceData deviceData = DeviceData.builder()
                        .iotId(iotId)
                        .functionId(key)
                        .dataValue(value.toString())
                        .alarmTime(finalEventTime)
                        .deviceName(device.getDeviceName())
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .accessLocation(device.getBindingLocation())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .build();

                list.add(deviceData);
            });

            // 3. 批量保存
            saveBatch(list);


            // 新增的逻辑： 4. 把最新数据存入redis
            redisTemplate.opsForHash().put(RedisKeyConstants.IOT_DEVICE_LAST_DATA, iotId, list);
        });
    }
    }